package com.ruoyi.common.sms.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class AliSmsTemplate {

    @Autowired
    private AliyunSmsProperties smsProperties;

    private IAcsClient client;

    @PostConstruct
    public void init() {
        DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(), smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
        this.client = new DefaultAcsClient(profile);
    }

    /**
     * 同步发送短信
     * @param mobile 手机号（11位）
     * @param templateCode 模板CODE
     * @param paramJson 模板变量JSON，如 {"code":"1234"}
     */
    public SmsResult sendSms(String mobile, String templateCode, Map<String, String>  paramJson) {
        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumbers(mobile);
        req.setSignName(smsProperties.getSignName());
        req.setTemplateCode(templateCode);
        req.setTemplateParam(convertTemplateParam(paramJson));

        try {
            SendSmsResponse rsp = client.getAcsResponse(req);
            if ("OK".equals(rsp.getCode())) {
                return SmsResult.success("发送成功", rsp.getRequestId(), rsp.getBizId());
            }
            // 阿里云返回业务错误
            log.warn("短信发送失败,code={},msg={}", rsp.getCode(), rsp.getMessage());
            return SmsResult.error(rsp.getMessage(), rsp.getCode(), rsp.getRequestId());

        } catch (ClientException e) {
            log.error("短信SDK异常", e);
            return SmsResult.error("网络异常，请稍后重试", null, null);
        }
    }

    /**
     * 异步发送（线程池）
     */
    public CompletableFuture<SmsResult> sendAsync(String mobile, String templateCode, Map<String, String> paramJson) {
        return CompletableFuture.supplyAsync(() -> sendSms(mobile, templateCode, paramJson));
    }

    /**
     * 转换模板参数为JSON字符串
     */
    private String convertTemplateParam(Map<String, String> templateParam) {
        if (templateParam == null || templateParam.isEmpty()) {
            return "{}";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        boolean first = true;
        for (Map.Entry<String, String> entry : templateParam.entrySet()) {
            if (!first) {
                sb.append(",");
            }
            sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
            first = false;
        }
        sb.append("}");
        return sb.toString();
    }
}
